//==================路由鉴权========================
import router from "@/router";
// progress bar
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// NProgress Configuration
NProgress.configure({ showSpinner: false });
//获取白名单
import whiteMenu from "@/router/whiteMenu";
//获取user的pinia
import useUserStore from "@/store/modules/user";
import pinia from "@/store";
const userStore = useUserStore(pinia);

// 全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  NProgress.start();
  //设置title
  if (to.name && to.name != "" && to.name != "undefined") {
    document.title = import.meta.env.VITE_APP_TITLE + "-" + to.name;
  } else {
    document.title = import.meta.env.VITE_APP_TITLE;
  }
  //检查token
  if (userStore.token_computed) {
    /* has token */
    if (to.path == "/user/login") {
      //登录成功之后，不能访问login
      next({ path: "/" });
    } else {
      console.log("****有token，放行****");
      //判断菜单逻辑
      let userMenu = userStore.menu_computed;
      if (!userMenu || userMenu == null) {
        await userStore.getUserMenu();
        userMenu = userStore.menu_computed;
        console.log("菜单权限", userMenu);
      }
      next();
    }
  } else {
    /* has not token */
    if (whiteMenu.indexOf(to.path) !== -1) {
      //在白名单请求中，放行
      console.log("****没有token，在白名单，放行****");
      next();
    } else {
      next({ path: "/user/login", query: { redirect: to.fullPath } });
    }
  }
});

// 全局后置守卫
router.afterEach(() => {
  NProgress.done(); // finish progress bar
});
